import requests
from tqdm import tqdm


def tqdm_download(filename, url, chunk_size=9 * 1024 * 1024):
    resp = requests.get(url, stream=True)
    # 从响应头部信息获取文件的大小
    file_size = int(resp.headers["content-length"])  # 单位byte
    # 文件总大小，单位-字节，自动适应单位（MB、GB）：TRUE，单位之间的刻度为1024（默认1000），使用ASCII字符表示进度条，desc进度条描述
    with tqdm(total=file_size, unit="B", unit_scale=True, unit_divisor=1024, ascii=False, desc="下载文件描述") as bar:
        with requests.get(url, stream=True) as r:
            chunk_num = 1
            with open(f"{filename}.part{chunk_num}.mp4", "wb") as fp:
                for chunk in r.iter_content(chunk_size=chunk_size):
                    if chunk:
                        fp.write(chunk)
                        bar.update(len(chunk))

                    # 每写满一个 chunk，就创建一个新的文件
                    if fp.tell() >= chunk_size:
                        fp.close()
                        chunk_num += 1
                        fp = open(f"{filename}.part{chunk_num}.mp4", "wb")


tqdm_download(filename="a", url="https://vdept3.bdstatic.com/mda-qb1baapw54yvq60d/sc/cae_h264/1707746255058714028/"
                                    "mda-qb1baapw54yvq60d.mp4?v_from_s=hkapp-haokan-hna&auth_key=1713450384-0-0-"
                                    "4e1338e7231a33524cbcc9ec7997d3ab&bcevod_channel=searchbox_feed&cr=2&cd=0&pd=1&pt="
                                    "3&logid=1583998267&vid=17864728622130811776&klogid=1583998267&abtest=")
